#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Vergil
# datetime:2018/9/23 15:52
# software: PyCharm
import time
import login

from selenium import webdriver
from post_brush.post_collect import main as p_collect
from post_brush.post_click import main as p_click
from video_play.video_collect import main as v_collect
from video_play.video_brush import main as v_brush
from files_download.file_download import main as f_download
import logging
import sys

"""
使用pantomjs占用资源较少

"""
logger = logging.getLogger('main')
logger.setLevel(level=logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(
    executable_path="./chromedriver.exe",
    chrome_options=chrome_options)
# driver = webdriver.PhantomJS(executable_path="./phantomjs.exe")


def post(headers, course_name, browse_times):
    url_lst = p_collect(driver, course_name, browse_times)
    p_click(driver, url_lst, headers, browse_times)


def video(headers, course_name):
    parameters = v_collect(driver, headers, course_name)
    file_id_lst = parameters[0]
    course_id = parameters[1]
    class_id = parameters[2]

    v_brush(file_id_lst, headers, course_id, class_id)


def file_download(headers, course_name):
    f_download(driver, headers, course_name)


def main():
    headers_lst = []
    username = input('学号：').strip()
    password = input('密码：').strip()
    course_name = input('课程：').strip()
    i = int(input('请选择功能,刷帖输入1,看视频输入2,资料下载输入3：'))

    if i == 1:
        browse_times = input('刷帖次数：').strip()
        headers = login.main(driver, url, captcha_url, username, password)
        headers_lst.append(headers)
        post(headers, course_name, browse_times)

    elif i == 2:
        headers = login.main(driver, url, captcha_url, username, password)
        headers_lst.append(headers)
        video(headers, course_name)

    else:
        headers = login.main(driver, url, captcha_url, username, password)
        headers_lst.append(headers)
        file_download(headers, course_name)

    time.sleep(2)
    driver.close()


if __name__ == '__main__':
    url = 'https://spoc.tfswufe.edu.cn/'
    captcha_url = 'http://urp.tf-swufe.net:8080/cas/captcha.jpg'
    try:
        main()
        sys.exit()

    except Exception as e:
        logger.exception(e)
        input('请确保该路径存在且正确')
        sys.exit()
